<?php

/*
 * 支付		会员
 * Date		2018-4-14
 */

!defined('DEBUG') AND exit('Access Denied.');

$i = param(1);
//var_dump($i);exit;
switch ($i) {

    //登录 (通用)
    case "login":
        if ($user) header("Location:.");
        if ($method == 'GET') {
            $header['title'] = lang('user_login') . ' - ' . $conf['sitename'];
            include show_tpl('user_login.htm');
        } else {
            $username = param('username', '');
            $password = param('password', '');
            $vcode = param('vcode', '');
            if ($vcode != $_COOKIE['vcode']) message(0, '验证码错误');
            $arr = array(
                'username' => $username,
                'password' => $password,
            );
            $res = user_login($arr);
            message($res[0], $res[1]);
        }
        break;

    //注册 (通用)
    case "register":
        if ($method == 'GET') {
            if ($user) header("Location:.");
            $header['title'] = lang('user_register') . ' - ' . $conf['sitename'];
            include show_tpl('user_register.htm');
        } else {
            $username = param('username', '');
            $password = param('password', '');
            $email = param('email', '');
            $vcode = param('vcode', '');
            if (!isset($_COOKIE['vcode']) || $vcode != $_COOKIE['vcode']) message(0, '验证码错误');
            $arr = array(
                'username' => $username,
                'password' => $password,
                'email' => $email
            );
            $res = user_register($arr);
            message($res[0], $res[1]);
        }
        break;

    // 商户管理 (代理可用)
    case "manage":
        if (!$user) header("Location:.");
        if ($user['is_proxy'] == 0) exit;
        if ($method == 'GET') {
            $_uid = param(2);
            if ($_uid) {
                $_user = user_read($_uid);
                if ($_user['parent'] != $uid) exit;
                $header['title'] = '编辑费率 - ' . $conf['sitename'];
                include show_tpl('user_manage_rate.htm');
            } else {
                $column = param('column', 'all');
                $keyword = param('keyword', '');
                $page = param('page', 1);
                $pagesize = 10;
                $cond = array('parent' => $uid);
                if ($column != 'all') $cond[$column] = array('LIKE' => '%' . $keyword . '%');
                $userlist = db_find('user', $cond, array('login_time' => '-1'), $page, $pagesize);
                $pagination = pagination(url("user-manage") . '?column=' . $column . '&keyword=' . $keyword . '&page={page}', db_count('user', $cond), $page, $pagesize);
                $header['title'] = '商户管理 - ' . $conf['sitename'];
                include show_tpl('user_manage.htm');
            }
        } else {
            $_uid = param(2);
            $_user = user_read($_uid);
            if ($_user['parent'] != $uid) exit;
            $rate = param('rate');
            if ($rate < $user['rate']) message(0, '商户费率不能低于您的费率');
            $r = user__update($_uid, array('rate' => $rate));
            $r === FALSE AND message(-1, "更改失败");
            message(1, "更改成功");
        }
        break;

    // 商户添加 (代理可用)
    case "add":
        if (!$user) header("Location:.");
        if ($user['is_proxy'] == 0) exit;
        if ($method == 'GET') {
            $header['title'] = '商户添加 - ' . $conf['sitename'];
            include show_tpl('user_add.htm');
        } else {
            $username = param('username', '');
            $password = param('password', '');
            $email = param('email', '');
            $rate = param('rate');
            if ($rate < $user['rate']) message(0, '商户费率不能低于您自己的费率');
            $arr = array(
                'username' => $username,
                'password' => $password,
                'email' => $email,
                'rate' => $rate,
                'parent' => $uid
            );
            $res = user_register($arr);
            message($res[0], $res[1]);
        }
        break;

    // 会员中心 (通用)
    case "center":
        if (!$user) header("Location:" . url('user-login'));
        $notice = db_find('article', array('cid' => 1), array('time' => '-1'), 1, 11);
        $login_log = user_log_find(array('uid' => $uid, 'type' => '登录'));
        $cash_log = order_cash_find(array('uid' => $uid), 1, 5);
        $header['title'] = '商户后台 - ' . $conf['sitename'];
        include show_tpl('user_center.htm');
        break;

    // 会员信息 (通用)
    case "info":
        if (!$user) header("Location:" . url('user-login'));
        if ($method == 'GET') {
            $header['title'] = '基本资料 - ' . $conf['sitename'];
            include show_tpl('user_info.htm');
        } else {
            $mobile = param('phone');
            $qq = param('qq');
            $name = param('realname');
            $id = param('idcard');
            $sitename = param('sitename');
            $sitelink = param('siteurl');
            $is_mode=param('is_mode');
            if (preg_match('/[^0-9]+/', $mobile) || strlen($mobile) != 11) message(0, '手机号格式错误');
            if (preg_match('/[^0-9]+/', $qq) || strlen($qq) < 5 || strlen($qq) > 12) message(0, 'QQ号格式错误');
            if (preg_match('/[^0-9]+/', $id) || strlen($id) < 15) message(0, '身份证号码格式错误');
            if (strlen($name) < 2) message(0, '请输入真实姓名');
            $arr = array(
                'info_mobile' => $mobile,
                'info_qq' => $qq,
                'info_name' => $name,
                'info_id' => $id,
                'info_sitename' => $sitename,
                'info_sitelink' => $sitelink,
                'is_mode'=>$is_mode
            );
            user__update($uid, $arr);
            message(1, '资料更新成功');
        }
        break;

    // 会员密码 (通用)
    case "password":
        if (!$user) header("Location:" . url('user-login'));
        if ($method == 'GET') {
            $header['title'] = '修改密码 - ' . $conf['sitename'];
            include show_tpl('user_password.htm');
        } else {
            $pwd_type = param('pwd_type');
            $pwd1 = param('pwd1');
            $pwd2 = param('pwd2');
            $pwd3 = param('pwd3');
            if ($pwd2 != $pwd3) message(0, '两次密码输入不一致');
            if ($pwd_type == 0) {//修改登陆密码
                $arr = user_password_change(array('old' => $pwd1, 'new' => $pwd2));
                if ($arr[0] == 1) user_token_clear();
            } else {//修改提款密码
                $arr = user_password_change(array('old' => $pwd1, 'new' => $pwd2, 'type' => 1));
            }
            message($arr[0], $arr[1]);
        }
        break;

    // 退出登录 (通用)
    case "logout":
        if (!$user) header("Location:" . url('user-login'));
        user_token_clear();
        header("Location:.");
        break;

    // 会员日志 (通用)
    case "log":
        if (!$user) header("Location:" . url('user-login'));
        $type = param(2);
        switch ($type) {
            // 提现
            case "cash":
                //参数
                $status = param('status', '-1');    // 订单状态
                $number = param('number', '');    // 订单号
                $fdate = param('fdate', date('m/d/Y', strtotime('today') - 7 * 86400));    // 开始时间
                $tdate = param('tdate', date('m/d/Y', strtotime('today') + 86400));    // 结束时间
                $export = param('export', 0);    // 导出excel
                //条件
                $cond = array('uid' => $uid, 'time' => array('>=' => strtotime($fdate), '<=' => strtotime($tdate)));
                if ($status != '-1') $cond['status'] = $status;
                if ($number != '') $cond['number'] = $number;
                //导出excel
                if ($export) {
                    $log = order_cash_find($cond, 1, 10000);
                    if (!empty($log)) {
                        //colname
                        $colname = array('账单生成时间', '订单号', '发起金额', '手续费', '账单状态', '收款方式', '姓名', '账号');
                        //data
                        $data = array();
                        foreach ($log as $k => $v) {
                            $data[$k]['time'] = date('Y-m-d H:i:s', $v['time']);//账单生成时间
                            $data[$k]['number'] = ' ' . $v['number'];//订单号
                            $data[$k]['coin'] = $v['coin'];//发起金额
                            $data[$k]['fee'] = $v['fee'];//手续费
                            $data[$k]['status'] = $v['status'];//账单状态
                            $data[$k]['bank'] = $v['bank'] . ($v['is_dai'] == 1 ? '(代付)' : '');//收款方式
                            $data[$k]['name'] = ' ' . $v['name'];//姓名
                            $data[$k]['code'] = ' ' . $v['code'];//账号
                        }
                        //
                        $title = "结算记录 ($fdate-$tdate)";
                        $filename = '结算记录';
                        export_excel($title, $colname, $data, $filename);//下载excel
                    } else {
                        exit('没有数据');
                    }
                }
                $page = param('page', 1);
                $pagesize = 15;
                $log = order_cash_find($cond, $page, $pagesize);
                $param = '?status=' . $status . '&number=' . $number . '&fdate=' . $fdate . '&tdate=' . $tdate;
                $pagination = pagination(url("user-log-cash") . $param . '&page={page}', db_count('order_cash', $cond), $page, $pagesize);
                $tongji_total = db_find_one('order_cash', $cond, array(), array('sum(coin) as coin', 'count(*) as count'));
                $cond['status'] = '已审核';
                $tongji_get = db_find_one('order_cash', $cond, array(), array('sum(coin) as coin', 'count(*) as count'));
                $header['title'] = '结算记录 - ' . $conf['sitename'];
                include show_tpl('user_log_cash.htm');
                break;
            // 登录
            case "login":
                $page = param(3, 1);
                $pagesize = 15;
                $log = db_find('user_log', array('uid' => $uid, 'type' => '登录'), array('time' => '-1'), $page, $pagesize);
                $pagination = pagination(url("user-log-login-{page}"), db_count('user_log', array('uid' => $uid, 'type' => '登录')), $page, $pagesize);
                $header['title'] = '登录日志 - ' . $conf['sitename'];
                include show_tpl('user_log_login.htm');
                break;
        }
        break;

    // 交易订单 (通用 代理会员稍有不同)
    case "order":
        if (!$user) header("Location:" . url('user-login'));
        if($user['is_proxy']==1){
            $daili = 1;
        }else{
            $daili = 0;
        }
        //参数
        $status = param('status', -1);    // 订单状态
        $channel = param('channel', 0);    // 通道
        $merchant = param('merchant', '');    // 商户订单号
        $plat = param('plat', '');// 平台订单号
        $merchant_username = param('merchant_username', '');    // 商户帐号(仅代理可用)
        $fdate = param('fdate', date('Y-m-d H:i:s', strtotime('today')));    // 开始时间
        $tdate = param('tdate', date('Y-m-d H:i:s', strtotime('today') + 86399));    // 结束时间
        $export = param('export', 0);    // 导出excel
        //条件
        $cond = array();
        if($daili==1){
            $son_id = param('son_id');
            if($son_id)$cond['uid'] = $son_id;
        }

        // 代理可以按会员ID查询订单
        if ($daili == 1) {
            $cond['parent'] = $uid;
            if ($merchant_username != '') $cond['username'] = $merchant_username;
        } else {
            $cond['uid'] = $uid;
        }
        if ($status != -1) $cond['status'] = $status;
        if ($channel != 0) $cond['chid'] = $channel;
        if ($merchant != '') $cond['order_merchant'] = $merchant;
        $cond['time'] = array('>=' => strtotime($fdate), '<=' => strtotime($tdate));
        if ($plat != '') $cond['order_plat'] = $plat;
        //导出excel
        if ($export) {
            $log = db_find('order', $cond, array('time' => '-1'), 1, 10000);
            if (!empty($log)) {
                //colname
                $colname = array('订单时间', '商户帐号', '商户订单号', '平台订单号', '订单金额', '实付金额', '收入金额', '收款通道', '订单状态', '通知状态');
                if ($user['is_proxy'] != 1) unset($colname[1]);//商户帐号
                //data
                $data = array();
                foreach ($log as $k => $v) {
                    $data[$k]['time'] = date('Y-m-d H:i:s', $v['time']);//订单时间
                    if ($user['is_proxy'] == 1) $data[$k]['username'] = $v['username'];//商户帐号
                    $data[$k]['order_merchant'] = ' ' . $v['order_merchant'];//商户订单号
                    $data[$k]['order_plat'] = ' ' . $v['order_plat'];//平台订单号
                    $data[$k]['coin'] = $v['coin'];//订单金额
                    $data[$k]['coin_pay'] = $v['coin_pay'];//实付金额
                    $data[$k]['coin_merchant'] = $v['coin_merchant'];//收入金额
                    $data[$k]['channel'] = $v['channel'];//付款通道
                    $data[$k]['status'] = ($v['status'] == 0 ? '未支付' : '已支付');//订单状态
                    $data[$k]['notice_status'] = ($v['notice_status'] == 0 ? '未通知' : '已通知');//通知状态
                }
                //
                $title = "交易订单 ($fdate-$tdate)";
                $filename = '交易订单';
                export_excel($title, $colname, $data, $filename);//下载excel
            } else {
                exit('没有数据');
            }
        }
        if($daili==1){
            $sonsql = "select uid from pay_user where parent=$uid";
            $sonid = db_sql_find($sonsql);
            $sonstr = array_map('array_shift',$sonid);
            $sonstr = implode(',',$sonstr);
            $sql = "select * from pay_channel where uid in($sonstr)";
            $channels = db_sql_find($sql);
        }else{
            $channels = db_find('channel',array('uid'=>$uid));
        }

        $page = param('page', 1);
        $pagesize = 15;
        $log = db_find('order', $cond, ['time'=>'desc'], $page, $pagesize);
        if($daili==1) {
            $param = "?status=$status&son_id=$son_id&channel=$channel&merchant=$merchant&plat=$plat&merchant_username=$merchant_username&fdate=$fdate&tdate=$tdate";
        }else{
            $param = "?status=$status&channel=$channel&merchant=$merchant&plat=$plat&merchant_username=$merchant_username&fdate=$fdate&tdate=$tdate";
        }
        $pagination = pagination(url("user-order") . $param . "&page={page}", db_count('order', $cond), $page, $pagesize);
        $tongji_total = db_find_one('order', $cond, array(), array('count(*) as count', 'sum(coin) as total', 'sum(coin_merchant) as coin_merchant_total'));
        $cond['status'] = 1;
        $tongji_paid = db_find_one('order', $cond, array(), array('count(*) as count', 'sum(coin) as total'));
        $header['title'] = '交易订单 - ' . $conf['sitename'];
        $sonarr = db_find('user',array('parent'=>$uid));
        include show_tpl('user_order.htm');
        break;

    // 银行卡 (通用)
    case "bank":
        if (!$user) header("Location:" . url('user-login'));
        $bank = db_find('user_bank', array('uid' => $uid));
        if ($method == 'GET') {
            $header['title'] = '收款信息 - ' . $conf['sitename'];
            include show_tpl('user_bank.htm');
        } else {
            $bankname = param('bank');
            $code = param('code');
            $name = param('name');
            if (count($bank) >= $conf['bank_card_max']) message(0, '最多绑定' . $conf['bank_card_max'] . '张银行卡');
            if (strlen($bankname) < 4 || strlen($code) < 15) message(0, '银行卡信息错误');
            if (db_find_one('user_bank', array('bank' => $bankname, 'code' => $code))) message(0, '该银行卡已经被绑定');
            db_insert('user_bank', array('uid' => $uid, 'bank' => $bankname, 'code' => $code, 'name' => $name));
            message(1, '添加银行卡成功');
        }
        break;

    // 会员提现 (通用)
    case "cash":
        if (!$user) header("Location:" . url('user-login'));
        if ($method == 'GET') {
            $bank = db_find('user_bank', array('uid' => $uid));
            $header['title'] = '申请提现 - ' . $conf['sitename'];
            include show_tpl('user_cash.htm');
        } else {
            // 提款密码判断
            $password_ti = param('password_ti');
            if ($user['password_ti'] != md5(md5($password_ti) . $user['salt'])) message(0, '提款密码错误');
            // 金额判断
            $coin = (int)param('coin', 0);
            if ($coin < $conf['cash_min']) message(0, '最低提现' . $conf['cash_min'] . '元');
            if ($coin > $conf['cash_max']) message(0, '最高提现' . $conf['cash_max'] . '元');
            $coin = $coin + $conf['cash_fee_fixed'];
            if ($coin > $user['coin']) message(0, '您的余额不足以提现');
            //if(db_find_one('order_cash', array('uid'=>$uid,'status'=>'待审核'))) message(0, '您还有提现申请未处理，请耐心等待');
            // 银行判断
            $bank_id = param('bank');
            $bank = db_find_one('user_bank', array('id' => $bank_id));
            if (!$bank || $bank['uid'] != $uid) message(0, '银行信息错误，请重新绑定银行卡');
            // 数据库操作
            user__update($uid, array('coin-' => $coin));
            $arr = array(
                'uid' => $uid,
                'username' => $user['username'],
                'coin' => $coin,
                'number' => date('YmdHis') . rand(10000, 99999),
                'fee' => round($coin * $conf['cash_fee_percent'], 2) + $conf['cash_fee_fixed'],
                'bank' => $bank['bank'],
                'code' => $bank['code'],
                'name' => $bank['name'],
                'time' => $time
            );
            order_cash_insert($arr);
            // 后台提醒
            file_put_contents('tmp/remind-cash.txt', '1');
            $finance = db_sql_find("SELECT fid FROM " . $db->tablepre . "finance_power where uid=$uid");
            if (!empty($finance)) {
                foreach ($finance as $f) {
                    file_put_contents('tmp/remind-cash-' . $f['fid'] . '.txt', '1');
                }
            }
            message(1, '提现成功');
        }
        break;

    // 委托代付 (通用)
    case "cashAny":
        if (!$user) header("Location:" . url('user-login'));
        if ($method == 'GET') {
            $header['title'] = '委托代付 - ' . $conf['sitename'];
            include show_tpl('user_cashAny.htm');
        } else {
            // 提款密码判断
            $password_ti = param('password_ti');
            if ($user['password_ti'] != md5(md5($password_ti) . $user['salt'])) message(0, '提款密码错误');
            // 金额判断
            $coin = (int)param('coin', 0);
            $fee = round($coin * $conf['cash_fee_percent'], 2) + $conf['cash_fee_fixed'];
            $total = $coin + $fee;
            if ($coin < $conf['cash_min']) message(0, '最低提现' . $conf['cash_min'] . '元');
            if ($coin > $conf['cash_max']) message(0, '最高提现' . $conf['cash_max'] . '元');
            if ($total > $user['coin']) message(0, '您的余额不足以提现，需要' . $total . '元');
            //if(db_find_one('order_cash', array('uid'=>$uid,'status'=>'待审核'))) message(0, '您还有提现申请未处理，请耐心等待');
            // 银行判断
            $bank = param('bank', '');
            $code = param('code', '');
            $name = param('name', '');
            if ($bank == '' || $code == '' || $name == '') message(0, '银行信息错误，请重新填写');
            // 数据库操作
            user__update($uid, array('coin-' => $total));
            $arr = array(
                'uid' => $uid,
                'is_dai' => 1,
                'username' => $user['username'],
                'coin' => $coin,
                'number' => date('YmdHis') . rand(10000, 99999),
                'fee' => $fee,
                'bank' => $bank,
                'code' => $code,
                'name' => $name,
                'time' => $time
            );
            order_cash_insert($arr);
            // 后台提醒
            file_put_contents('tmp/remind-cash.txt', '1');
            $finance = db_sql_find("SELECT fid FROM " . $db->tablepre . "finance_power where uid=$uid");
            if (!empty($finance)) {
                foreach ($finance as $f) {
                    file_put_contents('tmp/remind-cash-' . $f['fid'] . '.txt', '1');
                }
            }
            message(1, '委托成功');
        }
        break;

    // 会员费率 (通用)
    case "rate":
        if (!$user) header("Location:" . url('user-login'));
        $header['title'] = '我的费率 - ' . $conf['sitename'];
        include show_tpl('user_rate.htm');
        break;

    // 接入信息 (会员可用)
    case "api":
        if (!$user) header("Location:" . url('user-login'));
        if ($user['is_proxy'] == 1) exit;
        $header['title'] = '接入信息 - ' . $conf['sitename'];
        include show_tpl('user_api.htm');
        break;

    case "store":
        if (!$user) header("Location:" . url('user-login'));
        $header['title'] = '店铺管理 - ' . $conf['sitename'];
        include show_tpl('user_store.htm');
        break;

    case "cateAdd":
        if (!$user) header("Location:" . url('user-login'));
        $name = param('name');
        $cate = db_insert('cate', array('name' => $name, 'uid' => $uid, 'status' => 1, 'is_public' => 2));
        if ($cate) {
            json(array('data' => '添加成功', 'status' => true));
        }
        json(array('data' => '添加失败', 'status' => false));
        break;

    case "storeUpdate":
        if (!$user) header("Location:" . url('user-login'));
        $id = (int)param('id');
        $name = param('name');
        $value = param('value');
        if (!is_int($id)) json(array('data' => '请正确输入', 'status' => false));
        $cate = db_sql_find("SELECT id FROM " . $db->tablepre . "cate where uid=$uid and id=$id and status=1");
        if (!$cate) json(array('data' => '不存在的店铺', 'status' => false));
        $result = db_update("cate", array('id' => $id), array($name => $value));
        if ($result) {
            json(array('data' => '修改成功', 'status' => true));
        } else {
            json(array('data' => '修改失败', 'status' => false));
        }
        break;

    case 'storeCate':
        if (!$user) header("Location:" . url('user-login'));
        $finance = db_sql_find("SELECT id,name FROM " . $db->tablepre . "cate where uid=$uid and status=1");
        json(['code' => 0, 'msg' => true, 'count' => 0, 'data' => $finance]);
        break;

    case  "storeDel":
        if (!$user) header("Location:" . url('user-login'));
        $id = (int)param('id');
        if (!is_int($id)) json(array('data' => '请正确输入', 'status' => false));
        $result = db_update("cate", array('uid' => $uid, 'id' => $id), array('status' => 2));
        if ($result) {
            json(array('data' => '删除成功', 'status' => true));
        } else {
            json(array('data' => '删除失败', 'status' => false));
        }
        break;

    case  "goods":
        if (!$user) header("Location:" . url('user-login'));
        $id = (int)param('id');
        if (!is_int($id)) json(array('data' => '请正确输入', 'status' => false));
        $cate = db_sql_find("SELECT id FROM " . $db->tablepre . "cate where uid=$uid and id=$id and status=1");
        if (!$cate) json(array('data' => '不存在的店铺', 'status' => false));
        $finance = db_sql_find("SELECT id,cid,price_start,price_end FROM " . $db->tablepre . "cate_price where cid=$id and status=1");
        json(['code' => 0, 'msg' => true, 'count' => 0, 'data' => $finance]);
        break;

    case "priceAdd":
        if (!$user) header("Location:" . url('user-login'));
        $price_start = param('price_start');
        $price_end = param('price_end');
        $cid = (int)param('cid');
        if (!is_int($cid)) json(array('data' => '请正确输入', 'status' => false));
        $cate = db_sql_find("SELECT id FROM " . $db->tablepre . "cate where uid=$uid and id=$cid and status=1");
        if (!$cate) json(array('data' => '不存在的店铺', 'status' => false));
        $cate = db_insert('cate_price', array('price_start' => $price_start, 'price_end' => $price_end, 'cid' => $cid, 'status' => 1));
        if ($cate) {
            json(array('data' => '添加成功', 'status' => true));
        }
        json(array('data' => '添加失败', 'status' => false));
        break;

    case "goodsUpdate":
        if (!$user) header("Location:" . url('user-login'));
        $id = (int)param('id');
        $cid = (int)param('cid');
        $name = param('name');
        $value = param('value');
        if (!is_int($id) && !is_int($cid)) json(array('data' => '请正确输入', 'status' => false));
        $cate = db_sql_find("SELECT id FROM " . $db->tablepre . "cate where uid=$uid and id=$cid and status=1");
        if (!$cate) json(array('data' => '不存在的店铺', 'status' => false));
        $result = db_update("cate_price", array('id' => $id, 'cid' => $cid), array($name => $value));
        if ($result) {
            json(array('data' => '修改成功', 'status' => true));
        } else {
            json(array('data' => '修改失败', 'status' => false));
        }
        break;

    case  "goodsDel":
        if (!$user) header("Location:" . url('user-login'));
        $cid = (int)param('cid');
        $id = (int)param('id');
        if (!is_int($id) && !is_int($cid)) json(array('data' => '请正确输入', 'status' => false));
        $cate = db_sql_find("SELECT id FROM " . $db->tablepre . "cate where uid=$uid and id=$cid and status=1");
        if (!$cate) json(array('data' => '不存在的店铺', 'status' => false));
        $result = db_update("cate_price", array('cid' => $cid, 'id' => $id), array('status' => 2));
        if ($result) {
            json(array('data' => '删除成功', 'status' => true));
        } else {
            json(array('data' => '删除失败', 'status' => false));
        }
        break;

    case  "goodsP":
        if (!$user) header("Location:" . url('user-login'));
        $id = (int)param('id');
        $cid = param('cid');
        if (!is_int($id) && !is_int($cid)) json(array('data' => '请正确输入', 'status' => false));
        $cate = db_sql_find("SELECT id FROM " . $db->tablepre . "cate where uid=$uid and id=$cid and status=1");
        $price = db_sql_find("SELECT id FROM " . $db->tablepre . "cate_price where cid=$cid and id=$id and status=1");
        if (!$cate && !$price) json(array('data' => '不存在的店铺', 'status' => false));
        $finance = db_sql_find("SELECT id,cid,pid,`name` FROM " . $db->tablepre . "cate_goods where pid=$id and cid=$cid and status=1");
        json(['code' => 0, 'msg' => true, 'count' => 0, 'data' => $finance]);
        break;

    case "goodsAdd":
        if (!$user) header("Location:" . url('user-login'));
        $name = param('name');
        $cid = (int)param('cid');
        $pid = (int)param('pid');
        if (!is_int($cid) && !is_int($pid)) json(array('data' => '请正确输入', 'status' => false));
        $cate = db_sql_find("SELECT id FROM " . $db->tablepre . "cate where uid=$uid and id=$cid and status=1");
        if (!$cate) json(array('data' => '不存在的店铺', 'status' => false));
        $cate = db_insert('cate_goods', array('name' => $name, 'pid' => $pid, 'cid' => $cid, 'status' => 1));
        if ($cate) {
            json(array('data' => '添加成功', 'status' => true));
        }
        json(array('data' => '添加失败', 'status' => false));
        break;

    case  "goodsPUpdate":
        if (!$user) header("Location:" . url('user-login'));
        $cid = (int)param('cid');
        $id = (int)param('id');
        $pid = (int)param('pid');
        $name = param('name');
        $value = param('value');
        if (!is_int($id) && !is_int($cid) && !is_int($pid)) json(array('data' => '请正确输入', 'status' => false));
        $cate = db_sql_find("SELECT id FROM " . $db->tablepre . "cate where uid=$uid and id=$cid and status=1");
        if (!$cate) json(array('data' => '不存在的店铺', 'status' => false));
        $result = db_update("cate_goods", array('cid' => $cid, 'id' => $id, 'pid' => $pid), array($name => $value));
        if ($result) {
            json(array('data' => '修改成功', 'status' => true));
        } else {
            json(array('data' => '修改失败', 'status' => false));
        }
        break;

    case  "goodsPDel":
        if (!$user) header("Location:" . url('user-login'));
        $cid = (int)param('cid');
        $id = (int)param('id');
        $pid = (int)param('pid');
        if (!is_int($id) && !is_int($cid) && !is_int($pid)) json(array('data' => '请正确输入', 'status' => false));
        $cate = db_sql_find("SELECT id FROM " . $db->tablepre . "cate where uid=$uid and id=$cid and status=1");
        if (!$cate) json(array('data' => '不存在的店铺', 'status' => false));
        $result = db_update("cate_goods", array('cid' => $cid, 'id' => $id, 'pid' => $pid), array('status' => 2));
        if ($result) {
            json(array('data' => '删除成功', 'status' => true));
        } else {
            json(array('data' => '删除失败', 'status' => false));
        }
        break;
    case  "channel":

        if($user['is_proxy']==1){
            echo '你没有这个操作哦';exit;
        }
        $gateway = db_find('gateway', array(), array(), 1, 1000);
        $area = db_find('area', array(), array(), 1, 1000);
        $cate = db_find('cate', array(), array(), 1, 1000);
        //参数
        $page = param('page', 1);
        $page = $page < 1 ? 1 : $page;
        $pagesize = 10;
        $type = param('type', 0);    // 搜索类型
        $keywords = trim(param('keywords', ''));    // 关键字
        //条件
        $cond = '';
        if ($keywords != '') {
            switch ($type) {
                case 1://支付宝账号
                    $cond = " and  a.alipay_account like '%$keywords%'";
                    break;
                case 2://姓名
                    $cond = " and  a.alipay_realname like '%$keywords%'";
                    break;
                default://通道
                    $cond = " and  a.name like '%$keywords%'";
                    break;
            }
        }
        $sql1 = "select count(*)as num from pay_channel a INNER join pay_gateway b on a.gate_id=b.id INNER JOIN pay_cate c on c.id=a.cate INNER JOIN pay_user d on d.uid=a.uid where a.uid=$uid".$cond;
//       echo $sql1;exit;
        $num = db_sql_find_one($sql1);
        $num = $num['num'];
        $allpage = ceil($num / $pagesize);
        $page = $page > $allpage ? $allpage : $page;
        $start = ($page - 1) * $pagesize;
        $sql = "select a.*,b.shortname,b.name as gname,b.api_id,b.api_secret,b.api_publickey,b.url,b.status,c.name as catename,d.username from pay_channel a INNER join pay_gateway b on a.gate_id=b.id INNER JOIN pay_cate c on c.id=a.cate INNER JOIN pay_user d on d.uid=a.uid where a.uid =$uid".$cond;
        $sql .= $cond;
        $sql .= " limit $start,$pagesize";
        //查询
        $channel = db_sql_find($sql);
        $pagination = pagination(url("user-channel") . "?page={page}&type=$type&keywords=$keywords", $allpage, $page, $pagesize);
        $header['title'] = '通道管理 - ' . $conf['sitename'];
        include show_tpl("pay_channel.htm");
        break;
    case 'gatewayadd':
        if ($method == 'GET') {
            $header['title'] = "添加通道";
            $header['mobile_title'] = "添加通道";
            $users = db_find('user', array('is_proxy' => 1), array(), 1, 1000);
            $cate = db_find('cate', array('uid' => $uid, 'status' => 1), array(), 1, 1000);
            $area = db_find('area', array(), array(), 1, 1000);
//            var_dump($user);exit;
            include show_tpl("pay_gatewayadd.htm");

        } elseif ($method == 'POST') {
            $passcode = param('passcode');
            if (md5(md5($passcode) . 'ryTY45Rg') != $conf['passcode']) {
                message(0, '安全码错误');
                json(array('data' => '删除成功', 'status' => true));
            }
            $array = array();
            $array['shortname'] = param('shortname');
            $array['name'] = param('name');
            $array['api_id'] = param('api_id');
            $array['api_secret'] = param('api_secret');
            $array['api_publickey'] = param('api_publickey');
            $array['url'] = param('url');
            $r = db_insert('gateway', $array);
            $r === FALSE AND message(-1, "添加失败");
            message(0, "添加成功");
        }
        break;
    case 'upstatus':
        $id = param('id');
        $status = param('status');
        if (empty($id)) {
            json(array('data' => '数据丢失', 'code' => -1));
        }
        $re = db_update('channel', array('id' => $id, 'uid' => $uid), array('is_open' => $status));

        $re === FALSE AND json(array('data' => '设置失败', 'code' => -1));
        json(array('data' => '设置成功', 'code' => 1));
        break;
    case 'hebingadd':
        $id = param('a_id');
        if($conf['is_open_sms']){
            $smscode = param('b_smscode');
            $checksta = checkSms($smscode,$uid);
            if(!$checksta){
                json(array('data' => '验证码错误', 'code' => -1));
            }
        }
        if (empty($id)) {
            $a = array();
            $a['shortname'] = param('a_shortname');
            $a['name'] = param('a_name');

            $a['api_id'] = trim(param('a_api_id'));
            $a['api_secret'] = trim(param('a_api_secret'));
            $a['api_publickey'] = trim(param('a_api_publickey'));
            $a['url'] = param('a_url');
            foreach ($a as $v) {
                if (!$v || empty($v)) {
                    json(array('data' => '缺失参数', 'code' => 2));
                }
            }
            $re = db_insert('gateway', $a);
            if ($re === FALSE) {
                json(array('data' => '添加失败', 'code' => -1));
            }
            $b = array();
            $b['name'] = param('a_name');
            $b['alipay_account'] = param('b_alipay_account');
            $b['alipay_realname'] = param('b_alipay_realname');
            $b['uid'] = $uid;
            $b['max_price'] = param('b_max_price');
            $b['max_limit'] = param('b_max_limit');
            $b['gate_id'] = $re;
            $b['cate'] = param('b_cate');
            $b['is_open'] = param('b_is_open');
            $b['host'] = '127.0.0.1';
            foreach ($b as $v) {
                if (!$v || empty($v)) {
                    json(array('data' => '缺失参数', 'code' => 2));
                }
            }
            $b['area'] = param('b_area');
            $r = db_insert('channel', $b);
            if ($r === FALSE) {
                db_delete('gateway', array('id' => $re));
                json(array('data' => '添加失败', 'code' => -1));
            }
            if($conf['is_open_sms']){
                db_update('smscode',array('uid'=>$uid,'smscode'=>$smscode),array('status'=>1));
            }
            json(array('data' => '添加成功', 'code' => 0));
        } else {
            $a = array();
            db_sql_find_one('SET AUTOCOMMIT=0');
            $a['shortname'] = param('a_shortname');
            $a['name'] = param('a_name');
            $a['api_id'] = trim(param('a_api_id'));
            $a['api_secret'] = trim(param('a_api_secret'));
            $a['api_publickey'] = trim(param('a_api_publickey'));
            $a['url'] = param('a_url');
            foreach ($a as $v) {
                if (!$v || empty($v)) {
                    json(array('data' => '缺失参数1', 'code' => 2));
                }
            }
            $re = db_update('gateway', array('id' => $id), $a);
            if ($re === FALSE) {
                db_sql_find_one('ROLLBACK');
                json(array('data' => '修改失败', 'code' => -1));
            }
            $b = array();
            $b['name'] = param('a_name');
            $b['alipay_account'] = param('b_alipay_account');
            $b['alipay_realname'] = param('b_alipay_realname');
//            $b['uid'] = $uid;
            $b['max_limit'] = param('b_max_limit');
            $b['max_price'] = param('b_max_price');
            $b['cate'] = param('b_cate');
            $b['is_open'] = param('b_is_open');
            foreach ($b as $v) {
                if (!$v || empty($v)) {
                    json(array('data' => '缺失参数3', 'code' => 2));
                }
            }
            $b['area'] = param('b_area');
//        echo $id;exit;
            $r = db_update('channel', array('gate_id' => $id, 'uid' => $uid), $b);
            if ($r === FALSE) {
                db_sql_find_one('ROLLBACK');
                json(array('data' => '修改失败', 'code' => -1));

            }
            if($conf['is_open_sms']){
                db_update('smscode',array('uid'=>$uid,'smscode'=>$smscode),array('status'=>1));
            }
            db_sql_find_one('COMMIT');
            json(array('data' => '修改成功', 'code' => 1));
        }
        break;
    case 'delchannerl':
        if($conf['is_open_sms']) {
            $smscode = param('yzm');
            $smssta = checkSms($smscode, $uid);
            if (!$smssta) {
                json(array('data' => '验证码无效', 'code' => -1));
            }
        }
        db_sql_find_one('SET AUTOCOMMIT=0');
        $id = param('id');
        $arr = db_find_one('channel', array('id' => $id));
        if (!empty($arr) && $arr['uid'] == $uid) {
            $gate_id = $arr['gate_id'];
            $re = db_delete('channel', array('id' => $id));
            if ($re == FALSE) {
                db_sql_find_one('ROLLBACK');
                json(array('data' => '删除失败', 'code' => -1));
            }
            $r = db_delete('gateway', array('id' => $gate_id));
            if ($r == FALSE) {
                db_sql_find_one('ROLLBACK');

                json(array('data' => '删除失败', 'code' => -1));
            }
            if($conf['is_open_sms']) {
                db_update('smscode', array('uid' => $uid, 'smscode' => $smscode), array('status' => 1));
            }
            db_sql_find_one('COMMIT');

            json(array('data' => '删除成功', 'code' => 1));
        } else {
            json(array('data' => '不是的你的，你删锤子', 'code' => -1));
        }

        break;
    case 'gatewayup':
        $id = $_GET['2'];
//        if(empty($id)){
//            message(0, '没有选择数据');
//        }
        $header['title'] = "修改通道";
        $header['mobile_title'] = "修改通道";
        $users = db_find('user', array('is_proxy' => 1), array(), 1, 1000);
//        var_dump($users);exit;
        $cate = db_find('cate', array('uid' => $uid, 'status' => 1), array(), 1, 1000);
        $area = db_find('area', array(), array(), 1, 1000);

        $b = db_find_one('channel', array('id' => $id));
        if ($b['uid'] != $uid) {
            echo 'gg';
            exit;
        }
        $a = db_find_one('gateway', array('id' => $b['gate_id']));

        include show_tpl("pay_gatewayup.htm");
        break;
    case 'notice':
        $id = param('id');
        $orderData = db_find_one('order', ['id' => $id]);
        if (!empty($orderData) && $orderData['notice_data']) {
            $resCode = httpGet($orderData['notice_data']);
            if ($resCode ==200) {
                echo json_encode(['code'=>1,'msg'=>'通知成功']);
                exit();
            }else{
                echo json_encode(['code'=>0,'msg'=>'通知失败']);
                exit();
            }
        }
        break;
    case "sendSms":
        if(!$uid){
            echo 'gg';exit;
        }
        $phone = param('phone');
        $status = is_mobile_phone($phone);
        if(!$status){
            json(array('data' => '手机号不合法或者该账号没有手机号', 'code' => -1));
        }
        require APP_PATH."/sms/demo/sendSms.php";
        $code = randNum();
        $sta = sendSms($phone,$code);
        if($sta->Code=='OK'){
            $arr = array(
                'uid'=>$uid,
                'smscode'=>$code,
                'time'=>strtotime(date('Y-m-d H:i:s'))
            );
            $addsta = db_insert('smscode',$arr);

            json(array('data' => '发送成功', 'code' => 1,'smscode'=>$code));
        }else{
            json(array('data' => '短信发送失败哦，请联系管理员', 'code' => -1));
        }
        break;
}

function checkSms($code,$uid){
    $arr = db_find_one('smscode',array('uid'=>$uid,'smscode'=>$code));
    if(empty($arr)){
        return false;
    }elseif ($arr['status']==1){
        return false;
    }else{
        $now = strtotime(date('Y-m-d H:i:s'));
        if (($arr['time']+90)<$now) {
            return false;
        }else{
            return true;
        }

    }
}

function randNum(){
    $num = rand(1000,9999);
    return $num;
}


function is_mobile_phone ($mobile_phone)
{

    $chars = "/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$/";
    if(preg_match($chars, $mobile_phone))
    {
        return true;
    }

    return false;
}


function httpGet($url){
    $curl = curl_init();

    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, false);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // 设置请求时间  不超过3秒
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3);
    //执行命令
    $data = curl_exec($curl);
    // 获取请求后的状态码
    $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
    //关闭URL请求
    curl_close($curl);
    //显示获得的数据
    return $httpCode;
}

?>